#include "TestRopeJoint.h"
#include "Tools.h"

CCScene* TestRopeJoint::scene()
{
	CCScene* sc = CCScene::create();
	TestRopeJoint* layer = TestRopeJoint::create();
	sc->addChild(layer);

	return sc;
}

bool TestRopeJoint::init()
{
	BaseLayer::init();

	initJoint();

	scheduleUpdate();
	
	return true;
}

void TestRopeJoint::initJoint()
{
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;

	b2PolygonShape boxShape;
	boxShape.SetAsBox(1.0f, 1.0f);

	b2FixtureDef fixtureDef;
	fixtureDef.density = 1.0f;
	fixtureDef.friction = 0.3f;
	fixtureDef.restitution = 1.0f;
	fixtureDef.shape = &boxShape;

	b2Vec2 vec = Tools::convertTob2WorldSpace(ccp(winSize.width/2, winSize.height/2));
	b2Body* bodyA = NULL;
	{
		bodyDef.position.Set(vec.x, vec.y);
		bodyA = m_world->CreateBody(&bodyDef);
		bodyA->CreateFixture(&fixtureDef);
	}

	b2Body* bodyB = NULL;
	{
		bodyDef.position.Set(vec.x + 4, vec.y + 4);
		bodyB = m_world->CreateBody(&bodyDef);
		fixtureDef.restitution = 1.5f;
		bodyB->CreateFixture(&fixtureDef);
	}

	b2RopeJointDef jointDef;
	jointDef.bodyA = bodyA;
	jointDef.bodyB = bodyB;
	jointDef.localAnchorA = bodyA->GetLocalPoint(bodyA->GetPosition());
	jointDef.localAnchorB = bodyB->GetLocalPoint(bodyB->GetPosition());
	jointDef.maxLength = 6;
	jointDef.collideConnected = true;

	b2RopeJoint* joint = (b2RopeJoint*)m_world->CreateJoint(&jointDef);
}

void TestRopeJoint::update(float dt)
{
	m_world->Step(dt, 8, 1);
}